package com.drondea.testclient.handler.smgp;

import cn.hutool.core.util.StrUtil;
import com.drondea.sms.message.smgp30.msg.SmgpSubmitResponseMessage;
import com.drondea.testclient.handler.AbstractSubmitResponseHandler;
import com.drondea.testclient.panel.SmgpPanel;
import com.drondea.testclient.util.counter.SmgpAtomicUtil;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

/**
 * 测试收到的短信回应
 *
 * @author liuyanning
 */
@Sharable
@Slf4j
public class SmgpSubmitResponseHandler extends AbstractSubmitResponseHandler<SmgpSubmitResponseMessage> {

    private static final SmgpPanel PANEL = SmgpPanel.getInstance();

    @Override
    public void channelRead0(final ChannelHandlerContext ctx, SmgpSubmitResponseMessage msg) {

        log.debug("SmgpSubmitResponseHandler : {} : result: {} MsgId: {}", msg.getSequenceId(), msg.getStatus(), msg.getSmgpMsgId());
        PANEL.responseCountLabel.setText(StrUtil.format("响应数量: {}", SmgpAtomicUtil.RESPONSE_COUNT.incrementAndGet()));
        long result = msg.getStatus();
        if (result == 0) {
            PANEL.successCountLabel.setText(StrUtil.format("提交成功: {}", SmgpAtomicUtil.SUCCESS_COUNT.incrementAndGet()));
        } else {
            PANEL.failCountLabel.setText(StrUtil.format("提交失败: {}", SmgpAtomicUtil.FAIL_COUNT.incrementAndGet()));
        }

        // 当响应数量=发送数量时，设置结束时间
        if (SmgpAtomicUtil.SEND_COUNT.get() == SmgpAtomicUtil.RESPONSE_COUNT.get()) {
            calAvgSubmitSpeed(PANEL, SmgpAtomicUtil.SEND_COUNT.get() - PANEL.submitCountBefSend);
        }
    }
}
